package com.shop.controller;

import com.shop.pojo.User;
import com.shop.service.UserService;
import com.shop.service.UserServiceImpl;
import com.shop.util.Constants;
import com.shop.util.StrUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 消费者控制层
 * @author
 */
@WebServlet("/user")
public class UserController extends BaseServlet{
    public String login(HttpServletRequest request, HttpServletResponse response){
//        获取用户名
        String username = request.getParameter("username");
//        获取用户密码
        String password = request.getParameter("password");
//        获取验证码参数
        String code = request.getParameter("code");
//        获取用户是否要自动登录参数
        String auto = request.getParameter("auto");
//        判定用户名密码验证码不为空，如果为空跳转到登录界面
        if(StrUtils.empty(username) || StrUtils.empty(password) || StrUtils.empty(code)){
            request.setAttribute("msg","用户名，密码验证码均不能为空");
            return "forword:/login.jsp";
        }
//        调用service完成验证码的校验
        String sessionCode =(String) request.getSession().getAttribute("code");
        if(!code.equalsIgnoreCase(sessionCode)){
//            不对，跳转到登录界面
            request.setAttribute("username", username);
            request.setAttribute("password",password);
            return "forword:/login.jsp";
        }
//        判断用户名密码是否错误，如果错误返回提示信息
        UserService userService = new UserServiceImpl();
        User user = userService.login(username, password);
        if(user == null){
            request.setAttribute("userName", username);
            request.setAttribute("password", password);
            request.setAttribute("msg", "用户名或密码错误！");
            return "forward:/login.jsp";
        }
//        登陆成功，将用户信息放入tomcat的session会话携带
        request.getSession().setAttribute("loginuser" , user);
//                判断用户是否要自动登录，进行自动登录设置
        if("on".equals(auto)){
            Cookie cookie = new Cookie(Constants.AUTO_NAME, user.getUsername());
            cookie.setMaxAge(60*60*24*14);
            cookie.setPath("/");
//            通过响应讲Cookie写会到浏览器中保存
            response.addCookie(cookie);

        }
//        跳转到首页
        return "redirect:/index.jsp";
    }

}
